package com.ks.component.log;

import com.ks.common.model.LogRecord;
import com.ks.common.model.UriRemark;
import com.ks.common.util.CommonUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.TreeMap;

/**
 * 日志组件
 *
 * @author KingAusten
 * @date 2022/08/18 17:09:48
 */
@Slf4j
@Component
@AllArgsConstructor
public class LogComponent{

    /** redisson客户端 */
    private final RedissonClient redissonClient;

    @Async("LogThreadPoolExecutor")
    public void recordLog(HttpServletRequest request,Long accountNo){
        // TODO: 2022/8/18 从Redis 中获取 URL 对应的中文功能,将用户操作记录到日志表中

        // kingausten edit 2022/8/18 17:47 for:获取请求路径
        String requestURI = request.getRequestURI();
        RMap<String,UriRemark> uri = redissonClient.getMap("uri");
        UriRemark uriRemark = uri.get(requestURI);
        // kingausten edit 2022/8/18 17:52 for:获取不到 uri 路径对应的中文功能,则记录日志
        if(uriRemark == null){
            log.error("无法获取到请求路径:{}",requestURI);
            return;
        }
        String ipAddr = CommonUtil.getIpAddr(request);
        Map<String,String> allRequestHeader = CommonUtil.getAllRequestHeader(request);
        allRequestHeader.put("accountNo",accountNo.toString());
        // kingausten edit 2022/8/18 18:02 for: 生成日志对象
        LogRecord logRecord = LogRecord.builder()
                .event(uriRemark.getEvent())
                .data(allRequestHeader)
                .ip(ipAddr)
                .ts(System.currentTimeMillis())
                .bizId("")
                .build();

        String uuid=getDeviceId(logRecord);

        // TODO: 2022/8/18 访问设备地址和城市待实现
    }

    /**
     * 得到设备id
     *
     * @param logRecord 日志记录
     *
     * @return {@link String}
     */
    private String getDeviceId(LogRecord logRecord){
        Map<String,String> map = new TreeMap<>();
        map.put("ip",logRecord.getIp());
        map.put("event",logRecord.getEvent());
        Map<String,String> logRecordData = (Map<String,String>)logRecord.getData();
        map.put("userAgent",logRecordData.get("userAgent"));
        return CommonUtil.MD5(map.toString());
    }

}
